// QQLoginManager.swift
import UIKit
import SwiftUI

class SceneQQDelegate: NSObject, ObservableObject, TencentSessionDelegate {
    static let shared = SceneQQDelegate()
    var tencentOAuth: TencentOAuth!
    
    func initSDK() {
        TencentOAuth.setIsUserAgreedAuthorization(true)
        tencentOAuth = TencentOAuth()
        tencentOAuth.setupAppId(
            "102099029",
            enableUniveralLink: true,
            universalLink: "https://aiyuxm.com/qq_conn/102099029",
            delegate: self
        )
    }
    
    func login() {
        TencentOAuth.sharedInstance().accessToken = nil
        TencentOAuth.sharedInstance().openId = nil
        TencentOAuth.sharedInstance().expirationDate = nil
        // 或者直接调用登出方法（如果有）
        TencentOAuth.sharedInstance().logout(nil)
        
        
        let permissions = [kOPEN_PERMISSION_GET_USER_INFO, kOPEN_PERMISSION_GET_SIMPLE_USER_INFO]
        tencentOAuth.authMode = .authModeClientSideToken
        tencentOAuth.authShareType = AuthShareType_QQ
        tencentOAuth.redirectURI = "tencent102099029://response"
        tencentOAuth.authorize(permissions)
    }
    
    // MARK: - TencentSessionDelegate
    func tencentDidLogin() {
        showLog("登陆成功")
        // 获取 Server Side Code（推荐方式）
//        if let code = tencentOAuth.getServerSideCode() {
//            showLog("✅ 授权 Code: \(code)")
//            getLogin(type: LoginType.QQ)?.doAuthSuc(code: code)
//        }
        
        // 如果需要直接获取 AccessToken（客户端模式）
        if let token = tencentOAuth.accessToken, let openId = tencentOAuth.openId {
            showLog("⚠️ 客户端模式 Token: \(token)")
            showLog("OpenID: \(openId)")
            getLogin(type: LoginType.QQ)?.doAuthSuc(access_token: token, openid: openId)
        }
    }
    
    func tencentDidNotLogin(_ cancelled: Bool) {
        showToast("授权失败")
    }
    
    func tencentDidNotNetWork() {
        showToast("网络连接失败")
    }
}
